package com.example.migrator.batch;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisBatchItemWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MigrationItemWriter extends MyBatisBatchItemWriter<Object> {

    private static final Logger logger = LoggerFactory.getLogger(MigrationItemWriter.class);

    private String tableName;

    @Autowired
    public MigrationItemWriter(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        setSqlSessionFactory(sqlSessionFactory);
        setStatementId("com.example.migrator.mapper.MySQLMapper.insertBatch");
    }

    /**
     * 设置要写入的表名
     */
    public void setTableName(String tableName) {
        this.tableName = tableName;
        logger.info("设置写入表名为: {}", tableName);
    }

    @Override
    public void write(List<? extends Object> items) {
        if (items == null || items.isEmpty()) {
            logger.debug("没有数据需要写入");
            return;
        }

        // 构建参数，包含表名和数据列表
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("tableName", tableName);
        parameters.put("dataList", items);

        try {
            // 调用父类的方法执行批量插入
            super.write(items);
            logger.debug("成功写入 {} 条记录到表 {}", items.size(), tableName);
        } catch (Exception e) {
            logger.error("写入数据时发生错误: {}", e.getMessage(), e);
            throw new RuntimeException("数据写入失败", e);
        }
    }
}